package com.xiaoshuidi.cloud.framework.filings.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * RAS加密解密工具类
 * @author Feng
 */
public class RSAUtil {


    private static Base64.Decoder decoder;
    private static Base64.Encoder encoder;

    private static Logger log = LoggerFactory.getLogger(RSAUtil.class);


    static {
        decoder = Base64.getDecoder();
        encoder = Base64.getEncoder();
    }

    /**
     * index=0 privatekey
     * index=1 publickey
     *
     * @return
     */
    public static List<String> getKey() {
        List<String> keys = null;
        try {
            keys = new ArrayList<>();
            KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA");
            rsa.initialize(1024, new SecureRandom());
            KeyPair keyPair = rsa.generateKeyPair();
            PrivateKey aPrivate = keyPair.getPrivate();
            PublicKey aPublic = keyPair.getPublic();

            keys.add(encoder.encodeToString(aPrivate.getEncoded()));
            keys.add(encoder.encodeToString(aPublic.getEncoded()));
            return keys;

        } catch (NoSuchAlgorithmException e) {
            log.error("RAS公钥私钥生成失败，系统在开启加密时无法正常运行");
            log.error(e.getMessage());
        }

        return keys;
    }

    /**
     * 公钥加密
     *
     * @param data
     * @param publicKey
     * @return
     */
    public static String encryptPublicKeyRSA(String data, String publicKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey));
            byte[] res = cipher.doFinal(data.getBytes("UTF-8"));
            return encoder.encodeToString(res);
        } catch (Exception e) {
            log.error("RAS加密失败");
            log.error(e.getMessage());
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 私钥加密
     *
     * @param data
     * @return
     */
    public static String encryptPrivateKeyRSA(String data, String piKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, getPrivateKey(piKey));
            byte[] res = cipher.doFinal(data.getBytes("UTF-8"));
            return encoder.encodeToString(res);
        } catch (Exception e) {
            log.error("RAS加密失败");
            log.error(e.getMessage());
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 公钥解密
     *
     * @param data
     * @param publicKey
     * @return
     */
    public static String decryptPublicKeyRSA(String data, String publicKey) {
        try {
            byte[] bytes = decoder.decode(data.getBytes("UTF-8"));

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, getPublicKey(publicKey));

            return new String(cipher.doFinal(bytes));
        } catch (Exception e) {
            log.error("RAS公钥解密失败");
            log.error(e.getMessage());
        }
        return null;

    }


    /**
     * 私钥解密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String decryptPrivateKeyRSA(String data, String piKey) {
        try {
            byte[] bytes = decoder.decode(data.getBytes("UTF-8"));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(piKey));
            return new String(cipher.doFinal(bytes));
        } catch (Exception e) {
            log.error("RAS私钥解密失败");
            log.error(e.getMessage());
        }
        return null;

    }


    private static PublicKey getPublicKey(String publicKey) throws Exception {
        byte[] decode = decoder.decode(publicKey.getBytes());
        return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decode));

    }

    private static PrivateKey getPrivateKey(String privateKey) throws Exception {
        byte[] decode = decoder.decode(privateKey.getBytes());
        return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decode));
    }

    public static void main(String[] args) throws Exception {
        String s = "12312321321321";
        List<String> key = getKey();
        //私钥加密 公钥解密
        String enStr = encryptPrivateKeyRSA(s, key.get(0));
        System.out.println(decryptPublicKeyRSA(enStr, key.get(1)));

        String s1 = "sadasdasdas";

        //公钥加密 私钥解密
        String enStr2 = encryptPublicKeyRSA(s1, key.get(1));
        System.out.println(decryptPrivateKeyRSA(enStr2, key.get(0)));


    }
}